<?php

namespace Model;

use Nette\ArrayHash;
use Nette\DateTime;

use Dibi;

class PlacesModel extends BaseModel
{
	/**
	 * get Place
	 *
	 * @param  int $id
	 * @return array
	 */
	public function get($id)
	{
		$result = $this->db->select('p.*')
						   ->select("CONCAT_WS(' ', u.name, u.surname)")->as('nameUser')
						   ->from('places')->as('p')
						   ->join('users')->as('u')->on('u.id = p.user')
						   ->where('p.id = %i', $id)
						   ->fetch();

		return $result;
	}

	/**
	 * getAll Places
	 *
	 * @return connection
	 */
	public function getAll()
	{
		$result = $this->db->select('p.*')
						   ->select("CONCAT_WS(' ', u.name, u.surname)")->as('nameUser')
						   ->from('places')->as('p')
						   ->join('users')->as('u')->on('u.id = p.user');

		return $result;
	}

	/**
	 * insert Place
	 *
	 * @param array $values
	 * @throws DibiException
	 * @return INSERT_LAST_ID|DibiException
	 */
	public function insert($values)
	{
		try {
			if(!$values instanceof ArrayHash) {
				$values = ArrayHash::from($values);
			}

			$values->created = new DateTime;

			$success = $this->db->insert('places', $values)
							    ->execute(Dibi::IDENTIFIER);

			return $success;
		} catch (DibiException $e) {
			return $e;
		}
	}

	/**
	 * update Place
	 *
	 * @param int $id
	 * @param array $values
	 * @throws DibiException
	 * @return bool|DibiException
	 */
	public function update($id, $values)
	{
		try {
			if(!$values instanceof ArrayHash) {
				$values = ArrayHash::from($values);
			}

			$values->modified = new DateTime;

			$success = $this->db->update('places', $values)
								->where('id = %i', $id)
							    ->execute();

			return $success;
		} catch (DibiException $e) {
			return $e;
		}
	}

	/**
	 * delete Place
	 *
	 * @param int $id
	 * @throws DibiException
	 * @return bool|DibiException
	 */
	public function delete($id)
	{
		try {
			$success = $this->db->delete('places')
								->where('id = %i', $id)
								->execute();

			return $success;
		} catch (DibiException $e) {
			return $e;
		}
	}
}